package com.IO.stream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/***
 * @ClassName: Stream1
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 19:27 2022/1/29
 * @version : V1.0
 */
public class Stream1 {
    public static void main(String[] args) {
        streamRead();
        //streamWrite();
        //copy();
    }

    /**
     * @Param
     * @Description: 复制代码
     * @auther: TangGuoyi
     * @date: 23:31 2022/1/29
     * @return:
     */
    public static void copy() {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream("D:\\aaa.txt");
            fos = new FileOutputStream("D:\\bbb.txt",true);

            //创建缓冲区10个字节
            byte[] bytes = new byte[10];
            int count = 0;
            while ((count = fis.read(bytes))!= -1) {
                fos.write(bytes,0,count);

            }
            fis.close();
            fos.close();
            System.out.println("复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @Param
     * @Description: 字符流输入文件
     * @auther: TangGuoyi
     * @date: 23:17 2022/1/29
     * @return:
     */
    public static void streamRead() {
        FileInputStream fis = null;
        try {
            // 1 创建FileInputStream 并指定文件路径
            fis = new FileInputStream("d:\\aaa.txt");
            // 2 读取文件
            // fis.read();
            // 2.1单字节读取
            int data = 0;
            while((data = fis.read()) != -1){
                System.out.println(((char) data));
            }
            // 2.2 一次读取多个字节
            byte[] buf = new byte[3]; // 大小为3的缓存区
            int count = fis.read(buf); // 一次读3个
            System.out.println((new String(buf)));
            System.out.println((count));
            int count2 = fis.read(buf); // 再读3个
            System.out.println((new String(buf)));
            System.out.println((count2));

            // 上述优化后
            while((count = fis.read(buf)) != -1){
                System.out.println((new String(buf, 0, count)));
            }
            // 3 关闭
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Param
     * @Description: 字符流输出文件
     * @auther: TangGuoyi
     * @date: 23:17 2022/1/29
     * @return:
     */
    public  static void streamWrite() {
        FileOutputStream fos = null;
        try {
            //不覆盖继续追加写入
            fos = new FileOutputStream("d:\\bbb.txt",true);
            String var = "Hello World!\n";
            fos.write(var.getBytes());
            System.out.println("写入完成");
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
